package cjq.demo.nio.ch2_4;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Date;

/**
 * Created by cjq on 2016/4/18.
 */
public class ReadCompletionHandler implements CompletionHandler<Integer,ByteBuffer> {

    //用于读取半包消息和发送应答
    private AsynchronousSocketChannel channel ;
    public ReadCompletionHandler(AsynchronousSocketChannel channel){
        if(this.channel==null){
            this.channel = channel;
        }
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        attachment.flip();
        byte[] body = new byte[attachment.remaining()];
        attachment.get(body);
        try{
            String req = new String(body,"UTF-8");
            System.out.println("The time server receive order : "+req);
            String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(req)?
                    new Date(System.currentTimeMillis()).toString():"BAD ORDER";
            doWrite(currentTime);
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }


    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try{
            this.channel.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void doWrite(String currentTime) {
        if(currentTime!=null && currentTime.trim().length()>0){
            //调用字符串的解码方法将应答消息编码成字节数组，然后将它复制到发送缓冲区
            //最后调用AsynchronousSocketChannel的异步write方法
            byte[] bytes = currentTime.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer buffer) {
                    if(buffer.hasRemaining()){
                        channel.write(buffer,buffer,this);
                    }
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    try{
                        channel.close();
                    }catch (IOException e){
                        //ingore on close;
                    }
                }
            });
        }
    }
}
